package com.njy.utils;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.njy.pojo.Constant;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

@Component
public class Aes128Utils {
    private static final Logger log = LoggerFactory.getLogger(Aes128Utils.class);



    /**
     * 加密Encoder
     */
    private static final BASE64Encoder base64Encoder = new BASE64Encoder();
    /**
     * 解密Encoder
     */
    private static final BASE64Decoder base64Decoder = new BASE64Decoder();

    /**
     * 生成密钥
     *
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String generateKey() throws NoSuchAlgorithmException {
        KeyGenerator secretGenerator = KeyGenerator.getInstance(Constant.AES);
        SecureRandom secureRandom = new SecureRandom();
        secretGenerator.init(128);
        //设置加密用的种子，密钥,每次生成出来的密钥都是一样的。
       // secureRandom.setSeed(KEY.getBytes());
        SecretKey secretKey = secretGenerator.generateKey();
        return Base64.encodeBase64String(secretKey.getEncoded());
    }

    /**
     * 加密
     *
     * @param content 需要加密的字符串
     * @param key 密钥
     * @return
     * @throws Exception
     */
    public static String encode(String content, String key) {
        if (StringUtils.isAllBlank(content, key) ||
                key.length() != Constant.SECURITY_KEY_LEN) {
            log.error("待加密字符串[{}]串或秘钥[{}]错误！", content, key);
            return null;
        }
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(
                    key.getBytes(StandardCharsets.UTF_8), Constant.AES);
            // "算法/模式/补码方式"
            Cipher cipher = Cipher.getInstance(Constant.CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8.displayName()));
            // 此处使用BASE64做转码功能，同时能起到2次加密的作用。
            return base64Encoder.encode(encrypted);
        } catch (Exception e) {
            log.error("待加密字符串[{}]进行AES128加密失败！", content, e);
            return null;
        }
    }

    /**
     * 解密
     *
     * @param content 需要解密的字符串
     * @param key 密钥
     * @return
     */
    public static String decode(String content, String key) {
        if (StringUtils.isAllBlank(content, key) ||
                key.length() != Constant.SECURITY_KEY_LEN) {
            log.error("待解密字符串[{}]或秘钥[{}]错误！", content, key);
            return null;
        }
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8),
                    Constant.AES);
            Cipher cipher = Cipher.getInstance(Constant.CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            // 先用base64解密
            byte[] encrypted = base64Decoder.decodeBuffer(content);
            return new String(cipher.doFinal(encrypted),StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("待解密字符串[{}]进行AES128解密失败！", content, e);
            return null;
        }
    }


    public static void main(String[] args) {

/*

        String content = "{\"deptNo\":\"123\",\"deptName\":\"开发部\",\"dbSource\":\"dbSource1\"}";
        log.info("待加密：{}", content);
        String encodeStr = encode(content,"E1wgirdeQDo9WIM07/rpoQ==");
        log.info("加密后:{}", encodeStr);
        log.info("解密后：{}", decode("1d+B7F3khx8qFkZhIKfq3GQbOotOyglT/evqMVD3u+spvbS0JG8CP3DWO3dJl48me3UZRfpEsOla\nTqvM3RdLcw==","E1wgirdeQDo9WIM07/rpoQ=="));
*/

        /*JSONObject jsonObject = new JSONObject();
        jsonObject.put("key","E1wgirdeQDo9WIM07/rpoQ==");
        jsonObject.put("data","1d+B7F3khx8qFkZhIKfq3GQbOotOyglT/evqMVD3u+spvbS0JG8CP3DWO3dJl48me3UZRfpEsOla\nTqvM3RdLcw==");
        System.out.println(jsonObject.toJSONString());*/
        String  aesKey = "iuDR5UltVuwb98s1qrP50Q==";
        String aesKeyEncodeContent = "mHNTnP4+4sLqG1iGmK65bYeZomSO53hGIuvduikHNPPRGb53FuSlr9OyW7HqmreRsmWUPdKMRAiD\r\nVqq4PudQOQ==";
        log.info("解密后:{}", decode(aesKeyEncodeContent,aesKey));
    }
}
